#include "heroz_font.hh"
#include <cassert>
#include <stdexcept>
#include <string>
#include <SDL/SDL_image.h>

using namespace std;

HFont::HFont(const char *path, SDL_Surface *the_display) : display(the_display) {
  string fname;

  fname = path;
  fname += "/text_font";
  txtfont = IMG_Load(fname.c_str());
  if(!txtfont) throw runtime_error(SDL_GetError());
  fname = path;
  fname += "/graphics_font";
  gfxfont = IMG_Load(fname.c_str());
  if(!gfxfont) throw runtime_error(SDL_GetError());
}

HFont::~HFont() {
  assert(txtfont != NULL);
  SDL_FreeSurface(txtfont);
  assert(gfxfont != NULL);
  SDL_FreeSurface(gfxfont);
}


void HFont::gfx_at(short x, short y, int c) {
  SDL_Rect src;
  SDL_Rect dest = { x, y };

  assert(c >= 0 && c < 256);
  src.x = 0;
  src.w = 16;
  src.h = 16;
  src.y = 16 * c;
  SDL_BlitSurface(gfxfont, &src, display, &dest);
}


void HFont::print_at(short x, short y, const char *txt) {
  SDL_Rect src;
  SDL_Rect dest;
  Uint8 c;

  src.x = 0;
  src.w = txtfont->w;
  src.h = txtfont->w;
  dest.y = y;
  // dest.w = txtfont->w;
  // dest.h = txtfont->w;
  while(x < display->w && (c = *txt++)) {
      src.y = txtfont->w * c;
      dest.x = x;
      SDL_BlitSurface(txtfont, &src, display, &dest);
      x += txtfont->w;
  }
}

void HFont::print_at(short x, short y, const std::string &txt) {
  print_at(x, y, txt.c_str());
}
